package com.ews.onlineexchange.rest;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.ShortMessage;
import com.ews.onlineexchange.util.RestParamUtil;
import com.ews.onlineexchange.util.SqlUtil;

import net.sf.json.JSONObject;



@Path(value = "/sms")
@Transactional
public class SmsRest {
	private  String smsQuery = "SELECT shortMessage " 
			+	" FROM ShortMessage shortMessage";
	
	private  String smsCount = "SELECT count(shortMessage) " 
			+	" FROM ShortMessage shortMessage";
	@Inject
	EntityManager entityManager;
	@GET
	@Path("/getSmsList/{pageNumber}/{pageSize}/{destNumber}/{content}")
	@Produces("application/json")
	@Context
	public JSONObject getSmsList(@PathParam("pageNumber") int pageNumber,@PathParam("pageSize") int pageSize,
			@PathParam("destNumber") String destNumber,@PathParam("content") String content)  {
		
			destNumber = RestParamUtil.getParamValue(destNumber);
			content = RestParamUtil.getParamValue(content);
			StringBuilder sb = new StringBuilder(smsQuery);
			StringBuilder sbCount = new StringBuilder(smsCount);
			if(StringUtils.isNoneBlank(destNumber)) {
				if(sb.indexOf("WHERE") == -1) {
					sb.append(" WHERE  shortMessage.destNumber like :destNumber ");
					sbCount.append(" WHERE  shortMessage.destNumber like :destNumber ");
				}
			}
			
			if(StringUtils.isNoneBlank(content)) {
				if(sb.indexOf("WHERE") == -1) {
					sb.append(" WHERE  shortMessage.content like :content ");
					sbCount.append(" WHERE  shortMessage.content like :content ");
				}else {
					sb.append(" AND  shortMessage.content like :content ");
					sbCount.append(" AND  shortMessage.content like :content ");
				}
			}		
			sb.append(" ORDER BY shortMessage.sendTime desc");
			Query query = entityManager.createQuery(sb.toString());
			Query queryCount = entityManager.createQuery(sbCount.toString());
			query.setFirstResult((pageNumber - 1) * pageSize);
			query.setMaxResults(pageSize);
			if(StringUtils.isNoneBlank(destNumber)) {
				query.setParameter("destNumber", SqlUtil.getStringRestriction(destNumber));
				queryCount.setParameter("destNumber", SqlUtil.getStringRestriction(destNumber));
			}
			if(StringUtils.isNoneBlank(content)) {
				query.setParameter("content", SqlUtil.getStringRestriction(content));
				queryCount.setParameter("content", SqlUtil.getStringRestriction(content));
			}
			
			List<ShortMessage> smsList = query.getResultList();
			long count = (long)queryCount.getSingleResult();
			JSONObject json = new JSONObject();
			json.put("smsList", smsList);
			json.put("totalCount", count);
		return json;
	}
	
	
}
